const BaseController = require('./base');
const { sign, verify } = require('jsonwebtoken');
class Controller extends BaseController {
  constructor(...args) {
    super(...args);
    this.entity = 'user';
  }

  async signin() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body;
    const result = await app.mysql.get('user', { username, password });
    if (result) {
      const currentUser = JSON.parse(JSON.stringify(result));
      delete currentUser.password;
      const userRoles = await this.app.mysql.select('role_user', {
        where: { user_id: currentUser.id },
      });
      if (userRoles && userRoles.length > 0) {
        const roleIds = userRoles.map(item => item.role_id);
        if (roleIds) {
          const roles = await this.app.mysql.select('role', {
            where: { id: roleIds },
          });
          if (roles && roles.length > 0) {
            const roleCodes = roles.map(item => item.code);
            currentUser.roles = roleCodes;
          }
          let apis = [];
          const roleAPIs = await this.app.mysql.select('role_api', {
            where: { role_id: roleIds },
          });
          if (roleAPIs && roleAPIs.length > 0) {
            const apiIds = roleAPIs.map(item => item.api_id);
            const apisResult = await this.app.mysql.select('api', {
              where: { id: apiIds },
            });
            apis = apisResult;
          }
          currentUser.apis = apis;
        }
      }
      const accessToken = sign({ currentUser }, this.config.jwtSecret, {
        expiresIn: '1h',
      });
      const refreshToken = sign({ currentUser }, this.config.jwtRefreshSecret, {
        expiresIn: '7d',
      });
      this.success({
        access_token: accessToken,
        refresh_token: refreshToken,
      });
    } else {
      this.error('登录失败');
    }
  }
  async refreshAccessToken() {
    const { ctx } = this;
    const refreshToken = ctx.request.body.refresh_token;
    if (!refreshToken) {
      return this.error('缺少 refresh token');
    }
    try {
      const decoded = verify(refreshToken, this.config.jwtRefreshSecret);
      const user = decoded.user;
      const accessToken = sign({ user }, this.config.jwtSecret, {
        expiresIn: '1h',
      });
      this.success({
        refreshToken,
        access_token: accessToken,
      });
    } catch (error) {
      this.error('无效的 refresh token');
    }
  }
  async menus() {
    const currentUser = this.ctx.session.currentUser;
    let menus = [];
    if (currentUser) {
      const roleResult = await this.app.mysql.get('role_user', {
        user_id: currentUser.id,
      });
      if (roleResult) {
        const role = await this.app.mysql.get('role', {
          id: roleResult.role_id,
        });
        if (role) {
          const menuResult = await this.app.mysql.select('role_menu', {
            where: { role_id: role.id },
          });
          if (menuResult && menuResult.length > 0) {
            const menuIds = menuResult.map(item => item.menu_id);
            if (menuIds) {
              const menusResult = await this.app.mysql.select('menu', {
                where: { id: menuIds },
              });
              menus = menusResult;
            }
          }
        }
      }
    }
    this.success({
      menus,
    });
  }

  async signup() {
    const { ctx, app } = this;
    const user = ctx.request.body;
    const result = await app.mysql.insert('user', user);
    if (result.affectedRows > 0) {
      this.success({
        id: result.insertId,
      });
    } else {
      this.error('注册失败');
    }
  }
}
module.exports = Controller;
